<template>
  <div class="mod-config">
    <el-row>
      <el-col :span="8" style="background-color: aliceblue;">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
              <span>字典列表</span>
              <el-button size="mini" v-if="isAuth('base:basedict:save')" type="primary" icon="el-icon-plus" style="float: right;"
                @click="addOrUpdateHandle(0)">新增字典
              </el-button>
          </div>
          <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
            <el-form-item>
              <el-input size="mini" v-model="dataForm.key" placeholder="请输入父项名称或key" clearable @clear="getDataList()"
                @blur="getDataList()"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="success" @click="getDataList()" icon="el-icon-search">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="dataList" size="mini" v-loading="dataListLoading" :row-class-name="tableRowClassName"
            style="width: 100%;"
            :row-style="{height: '36px', padding: '0px', margin: '0'}"
            :cell-style="{padding: '0'}"
            @row-click="getItemData"
            @cell-dblclick="cellClick"
            :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
            <el-table-column prop="name" sortable header-align="center" align="center" label="父项名称">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.name" v-if="showInput == `name${scope.row.dictId}`"
                  @blur='blurInput(scope.row, "name", scope.row.name)' v-focus>
                </el-input>
                <span v-else>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" sortable header-align="center" align="center" label="父项编码">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.code" v-if="showInput == `code${scope.row.dictId}`"
                  @blur='blurInput(scope.row, "code", scope.row.code)' v-focus>
                </el-input>
                <span v-else>{{scope.row.code}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" header-align="center" align="center" label="状态" width="65px">
              <template slot-scope="scope">
                <el-switch size="mini" v-model="scope.row.status" @change="stateChanged(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="scope">
                <el-button type="text" class="btn-delete" round size="mini" v-if="isAuth('base:basedict:delete')"
                  @click="deleteHandle(scope.row.dictId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="pageIndex"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                :total="totalPage"
                layout="total, sizes, prev, pager, next, jumper">
              </el-pagination>
        </el-card>
      </el-col>
      <!-- 子表 -->
      <el-col :span="15" style="margin-left: 28px;">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
              <span>字典明细</span>
              <el-button size="mini" v-if="isAuth('base:basedictitem:delete')" type="danger" icon="el-icon-delete"
                @click="deleteItemHandle()" style="float: right; margin-left: 5px;">批量删除
              </el-button>
              <el-button size="mini" v-if="isAuth('base:basedictitem:add')" type="primary" icon="el-icon-plus"
                @click="addItemHandle(0)" style="float: right; margin-right: 5px;">新增明细
              </el-button>
          </div>
          <el-table  :data="itemDataList" size="mini" v-loading="dataListLoading" style="width: 100%;"
            @cell-click="itemCellClick" @selection-change="selectionItemChangeHandle"
            :row-style="{height: '36px', padding: '0px', margin: '0'}" :cell-style="{padding: '0'}"
            :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
            <el-table-column type="selection" header-align="center" align="center" width="50">
            </el-table-column>
            <el-table-column type="index" header-align="center" align="center" width="50" label="序号">
            </el-table-column>
            <el-table-column prop="label" sortable header-align="center" width="180px" align="center" label="字典项名称">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.label" v-if="showItemInput == `label${scope.row.itemId}`"
                  @blur='blurItemInput(scope.row, "label", scope.row.label)' v-focus>
                </el-input>
                <span v-else>{{scope.row.label}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="value" sortable header-align="center" width="140px" align="center" label="字典项值">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.value" v-if="showItemInput == `value${scope.row.itemId}`"
                  @blur='blurItemInput(scope.row, "value", scope.row.value)' v-focus>
                </el-input>
                <span v-else>{{scope.row.value}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" sortable header-align="center" width="200px" align="center" label="修改时间">
            </el-table-column>
            <el-table-column prop="status" header-align="center" align="center" label="状态">
              <template slot-scope="scope">
                <!-- <el-tag v-if="scope.row.status==1" type="success">启用</el-tag>
                <el-tag v-else type="warning">禁用</el-tag> -->
                <el-switch size="mini" v-model="scope.row.status" @change="itemStateChanged(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="scope">
                <!-- <el-button type="text" size="mini" v-if="isAuth('goods:goods:modify')" @click="saveCurrentRowHanlde()">保存
                </el-button> -->
                <el-button type="text" class="btn-delete" round size="mini" v-if="isAuth('base:basedictitem:delete')"
                  @click="deleteItemHandle(scope.row.itemId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <add-item v-if="addItemVisible" ref="addItem" @refreshDataList="getItemDataList"></add-item>
  </div>
</template>

<script>
  import AddOrUpdate from './basedict-add-or-update'
  import addItem from './basedictitem-add-or-update'
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        itemDataList: [],
        dictId: null,
        dictItemId: null,
        dataListLoading: false,
        addOrUpdateVisible: false,
        addItemVisible: false,
        selectedDict: {},
        showInput: false,
        oldData: {},
        showItemInput: false,
        oldItemData: {},
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      }
    },
    components: {
      AddOrUpdate,
      addItem
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
    computed: {
      // selectedDict() {
      //   if(!this.selectedDict.name){
      //     return this.dataList[0]
      //   }
      //   return this.selectedDict
      // }
    },
    activated() {
      this.getDataList(0)
    },
    methods: {
      //单选框事件
      getTemplateRow(index, row) { //获取选中数据
        this.$nextTick(() => {
          this.selectedDict = row;
          this.dictId = row.dictId;
          this.getItemDataList();
        })
      },
      getItemData(row, column, cell, event){
        this.$nextTick(() => {
          this.selectedDict = row;
          this.dictId = row.dictId;
          this.getItemDataList();
        })
      },
      // 把每一行的索引放进row
      tableRowClassName({
        row,
        rowIndex
      }) {
        row.index = rowIndex;
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        if (this.oldData[name] != value) {
          const res = await this.$confirm('此次修改将影响其他关联的数据查询, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);

          if (res === 'confirm') {
            row[name] = value
            //保存数据
            this.saveDict(row)
          }
        }
        this.showInput = ""
      },
      //单元格点击
      cellClick(row, column, cell, event) {
        this.showInput = column.property + row.dictId
        this.oldData[column.property] = row[column.property]
      },
      async saveDict(dict) {
        dict.status = dict.status ? 1 : 0
        const res = await this.$http({
          url: `/base/basedict/update`,
          method: 'post',
          data: this.$http.adornData(dict)
        })
        let data = res.data
        if (data && data.code === 0) {
          this.$message.success('操作成功')
          this.getDataList()
        }
      },
      // 当input失去光标后进行的操作
      async blurItemInput(row, name, value) {
        if (this.oldItemData[name] != value) {
          const res = await this.$confirm('此次修改将影响其他关联的数据查询, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);

          if (res === 'confirm') {
            row[name] = value
            //保存数据
            this.saveDictItem(row)
          }
        }
        this.showItemInput = ""
      },
      async saveDictItem(dictItem) {
        dictItem.status = dictItem.status ? 1 : 0
        const res = await this.$http({
          url: `/base/basedictitem/update`,
          method: 'post',
          data: this.$http.adornData(dictItem)
        })
        let data = res.data
        if (data && data.code === 0) {
          this.$message.success('操作成功')
          this.getItemDataList()
        }
      },
      //单元格点击
      itemCellClick(row, column, cell, event) {
        this.showItemInput = column.property + row.itemId
        this.oldItemData[column.property] = row[column.property]
      },
      // 获取数据列表
      async getDataList(index) {
        this.dataListLoading = true
        const res = await this.$http({
          url: '/base/basedict/list',
          method: 'get',
          params: this.$http.adornParams({
            'key': this.dataForm.key,
            'page': this.pageIndex,
            'limit': this.pageSize,
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          data.page.list.forEach(item => {
            if (index === 0 && item.dictId === 0) {
              this.selectedDict = item;
            }
            return item.status = (item.status == 1 ? true : false)
          })
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          // this.getItemDataList()
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      // 获取数据列表
      async getItemDataList() {
        const res = await this.$http({
          url: `/base/basedict/listDictItem/${this.dictId}`,
          method: 'get'
        })
        let data = res.data
        if (data && data.code === 0) {
          data.data.forEach(item => {
            return item.status = (item.status == 1 ? true : false)
          })
          this.itemDataList = data.data
        } else {
          this.itemDataList = []
        }
      },
      async stateChanged(row) {
        let status = row.status ? 1 : 0
        const res = await this.$http.put(`/base/basedict/updateStatus/${row.dictId}/${status}`);
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getItemDataList();
      },
      async itemStateChanged(row) {
        let status = row.status ? 1 : 0
        const res = await this.$http.put(`/base/basedict/updateItemStatus/${row.itemId}/${status}`);
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
      },
      saveCurrentRowHanlde() {
      },
      // 新增 / 修改
      addOrUpdateHandle(type) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(type == 1 ? this.dictId : '')
        })
      },
      // 新增Item
      addItemHandle() {
        this.addItemVisible = true
        this.$nextTick(() => {
          this.$refs.addItem.init(this.selectedDict)
        })
      },
      // 多选
      selectionItemChangeHandle(val) {
        this.itemListSelections = val
      },
      // 删除
      async deleteItemHandle(id) {
        var ids = id ? [id] : this.itemListSelections.map(item => {
          return item.itemId
        })
        const res = await this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        if (res === 'confirm') {
          const result = await this.$http({
            url: '/base/basedictitem/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          })
          const data = result.data
          if (data && data.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getItemDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        }
      },
      // 删除
      async deleteHandle(id) {
        var ids = [id]
        const res = await this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        if (res === 'confirm') {
          const result = await this.$http({
            url: '/base/basedict/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          })
          const data = result.data
          if (data && data.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        }
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
    }
  }
</script>
<style lang="less" scoped>
  .btn-delete {
    text-decoration: underline;
  }
  .el-card__header {
    span{
      font-size: 16px;
    }
      padding: 12px 20px!important;
  }
</style>
